<template>
  <el-tabs
    v-model="activeTab"
    closable
    style="width: 100%"
    type="border-card"
    @tab-remove="tabRemove"
  >
    <template v-for="(item, key) in detailTabs" :key="key">
      <el-tab-pane :label="item.label" :name="item.label"></el-tab-pane>
    </template>
  </el-tabs>
  <el-button
    style="position: absolute; width: 80px; right: 10px; top: 4px"
    @click="addTab"
    >新增</el-button
  >
</template>

<script lang="ts" setup>
import { ref } from "vue";

/**
 * 所有的标签页
 */
const detailTabs = ref([
  {
    label: "标签页1",
  },
  {
    label: "标签页2",
  },
]);

/**
 * 当前展示的标签
 */
const activeTab = ref("标签页2");

const addTab = () => {
  const index = detailTabs.value.length + 1;
  detailTabs.value.push({
    label: "标签页" + index,
  });
};

const tabRemove = (targetName: string) => {
  const tabs = detailTabs.value;
  let activeTabName = activeTab.value;
  if (activeTabName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.label === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          activeTabName = nextTab.label;
        }
      }
    });
  }
  activeTab.value = activeTabName;
  detailTabs.value = tabs.filter((tab) => tab.label !== targetName);
};
</script>

<style scoped></style>
